package com.seestech.sell.service.impl;

import com.seestech.sell.common.exceptions.MyException;
import com.seestech.sell.common.utils.IdGen;
import com.seestech.sell.domain.mapper.ICustomerDao;
import com.seestech.sell.domain.model.Customer;
import com.seestech.sell.service.ICustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by idiot on 2017/7/10.
 */
@Service
public class CustomerServiceImpl implements ICustomerService {
    private static Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Resource
    private ICustomerDao customerDao;

    @Override
    public void insert(Customer info) {
        if(info.getId() == null)
            info.setId(IdGen.get().nextId());
        if(info.getCreateTime() == null)
            info.setCreateTime(new Date());
        if(customerDao.insert(info) < 1){
            logger.error("新增客户信息失败");
            throw new MyException("新增客户信息失败");
        }
    }

    @Override
    public void update(Customer info) {
        if(info.getUpdateTime() == null)
            info.setUpdateTime(new Date());
        if(customerDao.update(info) < 1){
            logger.error("修改客户信息失败");
            throw new MyException("修改客户信息失败");
        }
    }

    @Override
    public Customer getCustomerByCustomerId(String customerId) {
        return customerDao.getCustomerByCustomerId(customerId);
    }

    @Override
    public void modify(String customerId, double fee) {
        Customer customer = customerDao.getCustomerByCustomerId(customerId);
        if(customer != null){
            customer.setCount(customer.getCount()+1);   //交易记录加1
            customer.setTotalFee(customer.getTotalFee()+fee);   //交易金额
            if(customerDao.update(customer) < 1){
                logger.error("修改客户积分信息失败");
                throw new MyException("修改客户积分信息失败");
            }
        }
    }

    @Override
    public List<Customer> getCustomersByPhone(String phone) {
        return customerDao.getCustomersByPhone(phone);
    }
}
